package org.rqb.service;

import lombok.extern.slf4j.Slf4j;
import org.rqb.panel.QueryLANDevicesPanel;


import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

@Slf4j
public class LANDevicesService {
    private QueryLANDevicesPanel queryLANDevicesPanel;


    public LANDevicesService(QueryLANDevicesPanel queryLANDevicesPanel) {
        this.queryLANDevicesPanel = queryLANDevicesPanel;
    }

    /**
     * 查询当前设备局域网ip
     * @return
     */
    public String getCurrentIp(){
        try {
            // 获取所有网络接口
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();

            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaces.nextElement();

                // 获取该网络接口下的所有IP地址
                Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();

                while (inetAddresses.hasMoreElements()) {
                    InetAddress inetAddress = inetAddresses.nextElement();

                    // 只获取IPv4地址，且不包括回环地址(localhost)
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof java.net.Inet4Address) {
//                       log.info("本地局域网IP地址: " + inetAddress.getHostAddress());

                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

        return null;

    }


    /**
     * 查询局域网中的设备
     * @param vlan  网段
     * @param start  开始点
     * @param end  结束点
     */
    public void queryDevicesByInetAddress(String vlan,int start,int end) {
        if(start==end || start>end || start < 0 || end > 255) {
//            log.info("Ip地址范围是0~255");
            return;
        }

        String currentIp = getCurrentIp();
        int ipNum = Integer.parseInt(currentIp.substring(currentIp.lastIndexOf(".") + 1));

        for (int i = start; i <= end; i++) {

            String host = vlan + "." + i;
            final int currentIpIndex = i - 1;
            if (i == ipNum){ //表示是本机
                // 改变panel中的元素
                SwingUtilities.invokeLater(()->{
                    queryLANDevicesPanel.updateIpBtnBackground(currentIpIndex, Color.GREEN);
                });
                continue;
            }


//            log.info("当前ip " + host);
            if (isReachable(host)) { //可以找到该设备
                // 改变panel中的元素
                SwingUtilities.invokeLater(()->{
                    queryLANDevicesPanel.updateIpBtnBackground(currentIpIndex, Color.GREEN);
                });
            } else { //找不到该设备
                SwingUtilities.invokeLater(()->{
                    queryLANDevicesPanel.updateIpBtnBackground(currentIpIndex, Color.RED);
                });
            }
        }

    }

    // Ping设备并返回是否可达
    private static boolean isReachable(String ip) {
        try {
            InetAddress inetAddress = InetAddress.getByName(ip);
            return inetAddress.isReachable(1000); // 1秒超时
        } catch (IOException e) {
            return false;
        }
    }

}
